package com.ithinks.flow.common.utils.protocol.socket.aio.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * @Description
 * @ClassName AioWriterHandler
 * @Author MR.LI
 * @date 2020.12.07 18:11
 */
public class AioWriterHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel clientChannel;
    private CountDownLatch latch;

    public AioWriterHandler(AsynchronousSocketChannel clientChannel,CountDownLatch latch){
        this.clientChannel =clientChannel;
        this.latch = latch;
    }
    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        if(attachment.hasRemaining()){
            clientChannel.write(attachment,attachment,this);
        }else{
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            clientChannel.read(readBuffer,readBuffer,new AioReaderHandler(clientChannel,latch));
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            System.err.println("数据发送失败。。。。");
            clientChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
